<template>
  <text class="text-32" :class="[canGetCode?'color-t1':'color-t3']" @click="getCode">{{ codeText }}</text>
</template>

<script>
import { mobile } from '@/common/test'
import { getMobileNumber, createCodeCheckRegister } from '@/common/api/user'
export default {
  name: 'GetCode',
  props: {
    phone: {
      type: String,
      default: ''
    },
    codeFrom: {
      type: String,
      default: ''
    },
    check: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      codeText: '发送验证码',
      canGetCode: true
    }
  },
  methods: {
    // 获取验证码
    async getCode() {
      if (this.canGetCode) {
        if (!mobile(this.phone)) {
          this.toast('请输入正确的手机号')
          return
        }
        this.canGetCode = false
        const api = this.check ? createCodeCheckRegister : getMobileNumber

        let num = 60
        this.codeText = num + 's后重新获取'
        let timer = setInterval(() => {
          num--
          this.codeText = num + 's后重新获取'
          if (num <= 0) {
            this.codeText = '发送验证码'
            this.canGetCode = true
            clearInterval(timer)
            timer = null
          }
        }, 1000)

        const [err, res] = await api(this.phone, {
          codeFrom: this.codeFrom
        })
        if (!this.$http.errorCheck(err, res)) return false
        this.toast('获取验证码成功')
      }
    }
  }
}
</script>

<style scoped>
</style>
